<?php
namespace app\admin\module;

use app\admin\util\Token;
use app\common\model\Admin;
use app\common\model\Role;
use app\common\model\RolePermission;
use think\Db;
use think\Exception;

class RoleModule {
    public static function page($pageSize = 10){
        return Role::where([])->order('id','desc')->paginate($pageSize);
    }

    public static function create($data){
        $data['createtime'] = time();
        Role::create($data);
    }

    public static function update($data){
        $data['udatetime'] = time();
        Role::update($data,['id'=>$data['id']]);
    }

    public static function del($id){
        $exists = Admin::where(['role_id'=>$id])->find();
        if($exists){
            throw new Exception("该角色还在被【".$exists['nickname']."】使用，请先去掉");
        }
        \think\facade\Db::startTrans();
        try{
            RolePermission::where(['role_id'=>$id])->delete();
            Role::destroy($id);
            \think\facade\Db::commit();
        }catch (\Exception $e){
            \think\facade\Db::rollback();
            throw new Exception($e->getMessage());
        }
    }


    public static function permission($id){
        return RolePermission::where(['role_id'=>$id])->column("permission_id");
    }

    public static function savePermission($id,$permission){
        $data = [];
        foreach($permission as $val){
            array_push($data,['role_id'=>$id,'permission_id'=>$val]);
        }
        \think\facade\Db::startTrans();
        try {
            RolePermission::where(['role_id'=>$id])->delete();
            RolePermission::insertAll($data);
            \think\facade\Db::commit();
        }catch (\Exception $e) {
            \think\facade\Db::rollBack();
            throw new Exception($e->getMessage());
        }
    }
}